
// headul划入的效果
$('.headul li').hover(function () {
    // $(this).addClass('act').siblings().removerClass('act');
    $(this).addClass('act').siblings().removeClass('act');
}, function () {
    // console.log(1);
});
// 回到顶部
$(window).scroll(function () {
    if (scrollY > 220) {
        $('.top').show();
    } else {
        $('.top').hide();
    }
});
$('.top').click(function () {
    $('html').animate({
        scrollTop: 0
    }, 1000);
});

// 已登录
let denglu = document.querySelector('#login');
let login = getCookie('login');
login ? denglu.innerHTML = login : '';
denglu.onclick = function () {
    location.href = '../html/login.html';
    localStorage.setItem('url',location.href);
    return;
}


// 退出登录
login ? $('.exitdegnlu').show() : $('.exitdegnlu').hide();
$('.exitdegnlu').click(function () {
    console.log(1);
    setCookie('login', '111', '-1');
    location.href = '../html/login.html';
    localStorage.setItem('url',location.href);
    return;
});



// 跳转到购物车
$('.car').click(function () {
    if (!login) {
        alert('请先登录，在2s后跳转到登录界面');
        setTimeout(() => {
            location.href = '../html/login.html';
        }, 1000);

    } else {
        location.href = '../html/mycar.html';
    }

});


// 根据id来显示商品
let box = document.querySelector('.boxdetail');
if (!/id=\d+/.test(location.href)) {
    location.href = '../html/list.html';
}
let detailid = location.search.split('=')[1];
console.log(detailid);

async function getDeatil() {
    let res = await pAjax({
        url: '../../6.1xiang.php',
        data: {
            id: detailid,
        }
    });
    res = JSON.parse(res);
    // console.log(res);
    detailRunder(res.list);
    let b = new detailEnlarge('.boxdetail');
}
getDeatil();

function detailRunder(data) {
    console.log(data);
    let str = '';
    str += `
    <h5><i>${data.cat_id}</i>><i>${data.cat_one_id}</i>><i>${data.cat_three_id}</i></h5>

    <div class="show">
        <img src="${data.goods_big_logo}" />
        <div class="mask"></div>
    </div>
    <div class="list">
        <p class="active">
        <img midelImg="${data.goods_big_logo}" bigImg="${data.goods_big_logo}" src="${data.goods_big_logo}" />
        </p>
        <p>
            <img midelImg="../img/名创x可口可乐官网.jpg" bigImg="../img/名创x可口可乐官网.jpg" src="../img/名创x可口可乐官网.jpg" />
        </p>
        <p>
            <img midelImg="../img/天官赐福banner.jpg" bigImg="../img/天官赐福banner.jpg" src="../img/天官赐福banner.jpg" />
        </p>
        <p>
            <img midelImg="../img/腾讯QQ天生企鹅.jpg" bigImg="../img/腾讯QQ天生企鹅.jpg" src="../img/腾讯QQ天生企鹅.jpg" />
        </p>
        <p>
            <img midelImg="../img/官网首页滚动大图.jpg" bigImg="../img/官网首页滚动大图.jpg" src="../img/官网首页滚动大图.jpg" />
        </p>
    </div>
    <div class="enlarge">
    </div>

    <div class="itemInfo-wrap container">
        <div class="media-body">
            <h4 class="media-heading">小米 Redmi 小米 红米Note9pro/【享11重好礼】红米 Note9PRO5G手机全网通 湖光秋色 全网通8GB+256GB
            </h4>
            <div class="price">
                <i class="glyphicon glyphicon-yen"></i>
                <span>199.8</span>
            </div>
            <div class="btn-group" role="group" aria-label="...">
                <button type="button" class="btn btn-default">XL</button>
                <button type="button" class="btn btn-default">L</button>
                <button type="button" class="btn btn-default">M</button>
                <button type="button" class="btn btn-default">S</button>
                <button type="button" class="btn btn-default">XS</button>
            </div>

            <div>
                <button class="btn buynow btn-warning btn-lg buy">立即购买</button>
                <button class="btn addcar btn-danger btn-lg" idx="${data.goods_id}">加入/查看购物车</button>
            </div>
        
        </div>

    </div>
    <div class="detailintroduce">
       ${data.goods_introduce}
    </div>
        
    `;
    box.innerHTML = str;
    let enlarge = document.querySelector('.enlarge');
    enlarge.style.backgroundImage = `url(${data.goods_big_logo})`;
}


box.onclick = function (e) {
    let target = e.target;
    if (target.classList.contains('addcar')) {
        if (!login) {
            alert('请先登录，在2s后跳转到登录界面');
            setTimeout(() => {
                location.href = '../html/login.html';
            }, 1000);
            localStorage.setItem('url', location.href);
            return;
        }

        addcardata(login);
        
    }

    if (target.classList.contains('buynow')) {
        location.href = '../html/buy.html';
    }
}

async function addcardata(login) {
    let res = await pAjax({
        url: '../../6.2addCar.php',
        type: 'post',
        data: {
            username: login,
            goods_id: detailid,
        }
    });
    res = JSON.parse(res);
    console.log(res);
    if (res.code) {
        let flag;
        flag = confirm('添加成功，是否去到购物车页面');
        flag ? location.href = '../html/mycar.html' : '';
    }
}


//搜索过去列表页
let searchkbtn = document.querySelector('#searchkbtn');
let searchkey = document.querySelector('#searchkey');
searchkbtn.onclick = function () {
    localStorage.setItem('key',searchkey.value);
    location.href = `../html/list.html`;
}



// 放大镜
class detailEnlarge {
    constructor(ele) {
        this.ele = ele;
        this.init();
    }

    init() {
        this.box = document.querySelector(this.ele);
        this.show = this.box.querySelector('.show');
        this.mask = this.box.querySelector('.mask');
        this.enlarge = this.box.querySelector('.enlarge');
        this.p = this.box.querySelectorAll('.list p');
        this.ig = this.show.querySelector('img');

        this.show.onmouseenter = () => {
            this.mask.style.display = 'block';
            this.enlarge.style.display = 'block';
            this.setStyle();
        }

        this.show.onmousemove = () => {
            let e = window.event;
            this.move(e);
        }

        this.show.onmouseleave = () => {
            this.enlarge.style.display = 'none';
            this.mask.style.display = 'none';
        }

        this.p.forEach(item => {
            item.onclick = () => {
                this.Click(item);
            }
        });

    }

    move(e) {
        let x = e.clientX - this.box.offsetLeft - this.mask.offsetWidth / 2;
        let y = e.pageY - this.box.offsetTop - this.mask.offsetHeight / 2;
        if (x <= 0) {
            x = 0;
        }
        if (y <= 0) {
            y = 0;
        }
        if (x >= this.show.offsetWidth - this.mask.offsetWidth) {
            x = this.show.offsetWidth - this.mask.offsetWidth;
        }
        if (y >= this.show.offsetHeight - this.mask.offsetHeight) {
            y = this.show.offsetHeight - this.mask.offsetHeight;
        }
        this.mask.style.left = x + 'px';
        this.mask.style.top = y + 'px';
        // 鼠标移动的距离       背景图移动的大小
        // ------------- === -----------------
        //   show的大小         背景图大小

        // 背景图移动的距离 = 鼠标移动的距离 * 背景图大小 / show的大小
        this.bgX = -parseInt(x * this.bgW / this.show.offsetWidth);
        this.bgY = -parseInt(y * this.bgH / this.show.offsetHeight);
        this.enlarge.style.backgroundPosition = `${this.bgX}px ${this.bgY}px `;
    }

    Click(item) {
        for (let i = 0; i < this.p.length; i++) {
            this.p[i].className = '';
        }
        item.className = 'active';
        // 给p标签绑定点击的事件的时候 需要拿到这个p标签下面的子元素（img）
        let img = item.firstElementChild;
        //获取这个img标签中的 midelImg 属性的属性值  给show盒子中的图片设置路径
        let midel = img.getAttribute('midelImg');
        let big = img.getAttribute('bigImg');
        // console.log(big);
        this.ig.setAttribute('src', midel);
        // this.enlarge.setAttribute('background-image',`url(${big})`);
        this.enlarge.style.backgroundImage = `url(${big})`;
        // console.log();

    }


    setStyle() {
        this.showW = this.show.offsetWidth;
        this.showH = this.show.offsetHeight;
        this.maskW = parseInt(this.getStyle(this.mask, 'width'));
        this.maskH = parseInt(this.getStyle(this.mask, 'height'));
        this.bg = this.getStyle(this.enlarge, 'backgroundSize').split(' ');
        this.bgW = parseInt(this.bg[0]);
        this.bgH = parseInt(this.bg[1]);
        //  show       放大镜的背景图
        // ----- === -----------------
        // mask        放大镜盒子的宽度

        // 放大镜的宽高 = 放大镜的背景图 * mask / show
        this.enlarge.style.width = this.bgW * this.maskW / this.showW + 'px';
        this.enlarge.style.height = this.bgH * this.maskH / this.showH + 'px';
    }

    getStyle(ele, attr) {
        let style;
        if (window.getComputedStyle) {
            style = window.getComputedStyle(ele)[attr];
        } else {
            style = ele.currentStyle[attr];
        }
        return style;
    }


}